package com.abing.permissionsys.exception;

import com.abing.base.BaseResponse;
import com.abing.exception.CustomerErrorException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by  on 2019/1/9.
 *
 * @author mrpan
 * @version 0.0.2
 */
@Slf4j
@RestControllerAdvice
public class ExceptionController {

    // 捕捉其他所有异常
    @ExceptionHandler(Exception.class)
    public BaseResponse globalException(HttpServletRequest request, Throwable ex) {
        log.error(ex.getMessage(),ex);
        if(ex instanceof HttpRequestMethodNotSupportedException){
            return new BaseResponse(getStatus(request).value(),"请求方式错误，请检查后重试。", null);
        }else if(ex instanceof NoHandlerFoundException){
            return new BaseResponse(getStatus(request).value(),"接口名错误，请检查后重试。", null);
        }else if (ex instanceof CustomerErrorException){
            return new BaseResponse(((CustomerErrorException) ex).getCode(), ex.getMessage(), null);
        }else {
            return new BaseResponse(getStatus(request).value(), ex.getMessage(), null);
        }
    }


    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}